<template>
  <div class="container">
    <div class="header-section">
      <h1 class="page-title">全部品类</h1>
      <p class="page-subtitle">实惠的价格，也能买到设计精巧、功能实用的家居</p>
      <div class="search-wrapper">
        <img class="search-icon" src="" alt="search icon">
        <input class="search-input" type="search" placeholder="搜索产品系列" v-model="searchQuery">
      </div>
    </div>

    <div class="category-grid" v-if="filteredCategories.length > 0">
      <router-link
        v-for="category in filteredCategories"
        :key="category._id"
        :to="`/detail/${category._id}`"
        class="card"
      >
        <div class="card-image">
          <img :src="category.coverImage" :alt="category.name">
        </div>
        <div class="card-name">{{ category.name }}</div>
      </router-link>
    </div>

    <div class="empty-state" v-if="filteredCategories.length === 0 && searchQuery">
      <!-- <img class="empty-image" src="/empty-search.png" alt="No results"> -->
      <p class="empty-text">未找到相关的产品系列</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getCategories } from '@/services/api';

// --- 响应式状态 ---
const allCategories = ref([]); // 存储从API获取的完整列表
const searchQuery = ref(''); // 绑定到搜索框的输入内容

// --- 计算属性 ---
// 这是 Vue 实现实时搜索的核心，当 searchQuery 或 allCategories 变化时，它会自动重新计算
const filteredCategories = computed(() => {
  if (!searchQuery.value) {
    return allCategories.value;
  }
  const lowerCaseQuery = searchQuery.value.toLowerCase();
  return allCategories.value.filter(category => 
    category.name.toLowerCase().includes(lowerCaseQuery)
  );
});

// --- 生命周期钩子 ---
// 当组件挂载到页面上时，执行此函数
onMounted(async () => {
  try {
    const response = await getCategories();
    allCategories.value = response.data.data; // 将获取到的数据存入完整列表
  } catch (error) {
    console.error('获取品类列表失败:', error);
    // 在这里可以添加错误提示
  }
});
</script>